from celery import shared_task
import logging, json, datetime, base64, requests
from random import randint
from decimal import Decimal

from activities.models import ActivityQRCode, ActivityData, ActivityLevelRecord, Channel
from cashbonus.models import CashActivityData, CashActivityLevelRecord, CashActivity, CashActivityLevel


@shared_task
def detection_activity_qrcode(data):
    print(data)
    activityqrcode_id = data['activityqrcode_id']
    activityqrcode = ActivityData.objects.get(id=activityqrcode_id)
    if activityqrcode.state == 1:
        instance = activityqrcode.activity_level
        activity = instance.activity
        point = activityqrcode.point
        instance.take_point -= point
        instance.remain_point += point
        instance.p_take_point -= point
        instance.p_remain_point += point
        instance.save()
        activity.take_point -= point
        activity.remain_point += point
        activity.save()
        relation_set = instance.child_set.all()
        for relation in relation_set:
            parent = relation.parent
            parent.p_take_point -= 1
            parent.p_remain_point += 1
            parent.save()
        user = activityqrcode.companyuser
        activityqrcode.state = 4
        activityqrcode.save()
        activity_level_record_data = {}
        activity_level_record_data['point'] = point
        activity_level_record_data['operation_type'] = 6
        activity_level_record_data['activity_level_id'] = instance.id
        activity_level_record_data['remain_point'] = instance.remain_point
        activity_level_record_data['user_id'] = user.id
        activity_level_record_data['create_time'] = datetime.datetime.now()
        activity_level_record_data['level_id'] = user.level_id
        activity_level_record_data['remark'] = '派发过期回收'
        activity_level_record_data['activity_data_id'] = activityqrcode.id
        ActivityLevelRecord.objects.create(**activity_level_record_data)
        return '使二维码过期成功'
    return '二维码已被使用'


@shared_task
def detection_cash_activity_qrcode(data):
    print(data)
    activityqrcode_id = data['activityqrcode_id']
    activityqrcode = CashActivityData.objects.get(id=activityqrcode_id)
    if activityqrcode.state == 1:
        # instance = activityqrcode.cash_activity_level
        cash_activity_id = activityqrcode.cash_activity_id
        cash_activity_level_id = activityqrcode.cash_activity_level_id
        activity = activityqrcode.cash_activity
        if activity.activity_type in [1, 2, 3]:
            amount = activityqrcode.amount
            while True:
                activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                origin_take_amount = activity_level.take_amount
                origin_remain_amount = activity_level.remain_amount
                origin_p_take_amount = activity_level.p_take_amount
                origin_p_remain_amount = activity_level.p_remain_amount
                new_take_amount = origin_take_amount - amount
                new_remain_amount = origin_remain_amount + amount
                new_p_take_amount = origin_p_take_amount - amount
                new_p_remain_amount = origin_p_remain_amount + amount
                result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                          remain_amount=origin_remain_amount,
                                                          p_take_amount=origin_p_take_amount,
                                                          p_remain_amount=origin_p_remain_amount).update(
                    take_amount=new_take_amount, remain_amount=new_remain_amount, p_take_amount=new_p_take_amount,
                    p_remain_amount=new_p_remain_amount
                )
                if result == 0:
                    continue
                break
            while True:
                activity = CashActivity.objects.get(id=cash_activity_id)
                activity_origin_take_amount = activity.take_amount
                activity_origin_remain_amount = activity.remain_amount
                activity_new_take_amount = activity_origin_take_amount - amount
                activity_new_remain_amount = activity_origin_remain_amount + amount
                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                     remain_amount=activity_origin_remain_amount,
                                                     id=cash_activity_id).update(
                    take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                if result == 0:
                    continue
                break
            relation_set = activity_level.child_set.all()
            for relation in relation_set:
                parent = relation.parent
                parent.p_take_amount -= amount
                parent.p_remain_amount += amount
                parent.save()
            user = activityqrcode.companyuser
            activityqrcode.state = 4
            activityqrcode.save()
            try:
                cashactivitylevelrecord_data = {}
                cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                cashactivitylevelrecord_data['amount'] = amount
                cashactivitylevelrecord_data['operation_type'] = 6
                cashactivitylevelrecord_data['remain_amount'] = activity_level.remain_amount
                cashactivitylevelrecord_data['p_remain_amount'] = activity_level.p_remain_amount
                cashactivitylevelrecord_data['max_amount'] = activity_level.max_amount
                cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                cashactivitylevelrecord_data['user_id'] = user.id
                cashactivitylevelrecord_data['remark'] = '派发二维码过期'
                cashactivitylevelrecord_data['activity_data_id'] = activityqrcode.id
                cashactivitylevelrecord_data['activity_id'] = activity.id
                CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
            except Exception as e:
                print(e)
                pass
        else:
            amount = activityqrcode.amount
            while True:
                activity_level = CashActivityLevel.objects.get(id=cash_activity_level_id)
                origin_take_amount = activity_level.take_amount
                origin_max_amount = activity_level.max_amount
                origin_p_take_amount = activity_level.p_take_amount
                origin_p_max_amount = activity_level.p_max_amount
                new_take_amount = origin_take_amount - amount
                new_max_amount = origin_max_amount - amount
                new_p_take_amount = origin_p_take_amount - amount
                new_p_max_amount = origin_p_max_amount - amount
                result = CashActivityLevel.objects.filter(id=cash_activity_level_id, take_amount=origin_take_amount,
                                                          max_amount=origin_max_amount,
                                                          p_take_amount=origin_p_take_amount,
                                                          p_max_amount=origin_p_max_amount).update(
                    take_amount=new_take_amount, max_amount=new_max_amount, p_take_amount=new_p_take_amount,
                    p_max_amount=new_p_max_amount
                )
                if result == 0:
                    continue
                break
            while True:
                activity = CashActivity.objects.get(id=cash_activity_id)
                activity_origin_take_amount = activity.take_amount
                activity_origin_remain_amount = activity.remain_amount
                activity_new_take_amount = activity_origin_take_amount - amount
                activity_new_remain_amount = activity_origin_remain_amount + amount
                result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                     remain_amount=activity_origin_remain_amount,
                                                     id=cash_activity_id).update(
                    take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                if result == 0:
                    continue
                break
            relation_set = activity_level.child_set.all()
            for relation in relation_set:
                parent = relation.parent
                parent.p_take_amount -= amount
                parent.p_max_amount -= amount
                parent.save()
            user = activityqrcode.companyuser
            activityqrcode.state = 4
            activityqrcode.save()
            try:
                cashactivitylevelrecord_data = {}
                cashactivitylevelrecord_data['activity_level_id'] = activity_level.id
                cashactivitylevelrecord_data['amount'] = amount
                cashactivitylevelrecord_data['operation_type'] = 6
                cashactivitylevelrecord_data['activity_type'] = 2
                cashactivitylevelrecord_data['remain_amount'] = activity.remain_amount
                cashactivitylevelrecord_data['p_remain_amount'] = activity.remain_amount
                cashactivitylevelrecord_data['max_amount'] = activity.max_amount
                cashactivitylevelrecord_data['p_max_amount'] = activity_level.p_max_amount
                cashactivitylevelrecord_data['user_id'] = user.id
                cashactivitylevelrecord_data['remark'] = '派发二维码过期'
                cashactivitylevelrecord_data['activity_data_id'] = activityqrcode.id
                cashactivitylevelrecord_data['activity_id'] = activity.id
                CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
            except Exception as e:
                print(e)
                pass
        try:
            if activity.activity_type in [2, 5]:
                cash_activity_rule = activityqrcode.cash_activity_rule
                cash_activity_rule.probability += 1
                cash_activity_rule.save()
        except Exception as e:
            print(e)
            pass
        return '使二维码过期成功'
    return '二维码已被使用'


@shared_task
def capture_payeeFullName(data):
    print(data)
    activityqrcode_id = data['activityqrcode_id']
    activityqrcode = CashActivityData.objects.get(id=activityqrcode_id)
    url = 'https://mbillexprod.alipay.com/enterprise/fundReportDetailQuery.json'
    if activityqrcode.channel_id == 8:
        body = {
            'userId': '2088741038963832',
            'queryType': 'ALL',
            'pageSize': '1',
            'pageNum': '1'
        }
    else:
        body = {
            'userId': '2088631976752358',
            'queryType': 'ALL',
            'pageSize': '1',
            'pageNum': '1'
        }
    if activityqrcode.channel_id:
        platform = activityqrcode.channel
    else:
        platform = Channel.objects.filter(id=1, channel_type=2).first()
    headers = {
        'Cookie': platform.cookie,
        'referer': 'https://p.alipay.com/'
    }
    body['orderId'] = activityqrcode.payment_no
    try:
        response = requests.post(url=url, headers=headers, data=body)
        result = response.json()
        if result['status'] == 'succeed':
            activityqrcode.payeeFullName = result['result']['bizInfo']['payeeFullName']
            activityqrcode.save()
        return '同步支付宝付款账号成功'
    except:
        return '同步支付宝付款账号失败'
